package cn.fl.arbitration.web.apply.service.impl;

import cmm.comm.facade.upload.constant.SysUlFilesRecConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.arbitration.web.apply.service.IFileUploadService;
import cn.fl.arbitration.web.apply.vo.UpLoadFileRespVo;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.service.ISysUlFilesRecService;
import com.alibaba.fastjson.JSON;
import fl.constant.facade.framework.constant.UploadConstant;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import java.io.File;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

/**
 * @Auther: admin
 * @Date: 2018/9/12 20:43
 * @Description:
 */
@Service
public class FileUploadServiceImpl implements IFileUploadService {

    private static final Logger logger = LoggerFactory.getLogger(FileUploadServiceImpl.class);


    @Override
    public UpLoadFileRespVo upload(String filePath, MultipartHttpServletRequest multipartRequest) throws BaseException {
        try {
            JSONArray jsonArray = fileUpload(filePath, multipartRequest);
            logger.info("调用文件上传返回结果：{}", JSON.toJSONString(jsonArray));
            JSONObject o = jsonArray.getJSONObject(0);
            String url = o.getString("filePath");
            String fileNm = o.getString("fileNm");
            String serverPath = PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_SERVER_PATH);//服务地址
            String rootPath = PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_ROOT_PATH);//服务地址
            UpLoadFileRespVo upLoadFileRespVo = new UpLoadFileRespVo(serverPath + url, fileNm);
            upLoadFileRespVo.setAbsPath(rootPath+url);
            upLoadFileRespVo.setRelPath(url);
            return upLoadFileRespVo;
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            return null;
        }

    }

    public JSONArray fileUpload(String filePath,MultipartHttpServletRequest multipartRequest) throws BaseException {
        BaseLogUtils.info(logger, "upload", "文件上传B1", CurrentThreadContext.getCurrentUserName());
        JSONArray fileParams = new JSONArray();
        try {
            // 拼接存入路径-------->系统相对路径前缀 + 系统代码 + 模块(自定义) + 时间 + 文件
            String prifixPath = PropertiesCacheUtils.getProperty(cmm.comm.facade.upload.constant.UploadConstant.UPLOAD_ROOT_PATH);// 根目录
            StringBuffer savePath = new StringBuffer(prifixPath);// 最终保存路径
            if (!savePath.toString().endsWith(SysUlFilesRecConstant.SYS_FILE_PATH_SLASH)) {// 判断是否以"/"结尾,不是加入斜杠
                savePath.append(SysUlFilesRecConstant.SYS_FILE_PATH_SLASH);
            }
            savePath.append(PropertiesCacheUtils.getProperty(cmm.comm.facade.upload.constant.UploadConstant.UPLOAD_COSTOMER_PATH));// 自定义代码-其中包括系统代码
            if (StringUtils.isNotEmpty(filePath)) {// 如果不等于空则加入
                if (filePath.startsWith(SysUlFilesRecConstant.SYS_FILE_PATH_SLASH)) {// 判断是否以"/"开头
                    savePath.append(filePath.substring(1));
                } else {
                    savePath.append(filePath);
                }

            }
            BaseLogUtils.info(logger, "upload", "文件上传B2", CurrentThreadContext.getCurrentUserName());
            if (!savePath.toString().endsWith(SysUlFilesRecConstant.SYS_FILE_PATH_SLASH)) {// 判断是否以"/"结尾
                savePath.append(SysUlFilesRecConstant.SYS_FILE_PATH_SLASH);
            }
            String currentTime = DateUtils.formatDateToString(new Date(), DateUtils.YYYYMMDD);
            savePath.append(currentTime);
            savePath.append(SysUlFilesRecConstant.SYS_FILE_PATH_SLASH);
            BaseLogUtils.info(logger, "upload", "文件上传B3", CurrentThreadContext.getCurrentUserName());
            // 检查目录
            File pathFile = new File(savePath.toString());
            BaseLogUtils.info(logger, "upload", "文件上传B31->"+savePath.toString(), CurrentThreadContext.getCurrentUserName());
            if (!pathFile.exists()) {
                BaseLogUtils.info(logger, "upload", "文件上传B32", CurrentThreadContext.getCurrentUserName());
                // 文件夹不存 创建文件
                boolean createPath = pathFile.mkdirs();
                if (!createPath) {
                    BaseLogUtils.info(logger, "upload", "文件上传B33, 创建文件目录失败!" + createPath, CurrentThreadContext.getCurrentUserName());
                    throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "服务器附件目录未创建失败!");
                }
            }
            BaseLogUtils.info(logger, "upload", "文件上传B4", CurrentThreadContext.getCurrentUserName());

            Iterator<String> iter = multipartRequest.getFileNames();
            // 如果没有文件 抛出异常
            if (!iter.hasNext()) {
                BaseLogUtils.info(logger, "fileUpload", "文件上传失败,未选中文件内容.", CurrentThreadContext.getCurrentUserName());
                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "请选择要上传的文件!");
            }
            // 访问附件前缀地址
            // String serverPrefixPath =
            // PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_SERVER_PATH);
            BaseLogUtils.info(logger, "upload", "文件上传B", CurrentThreadContext.getCurrentUserName());
            // 创建返回的集合
            while (iter.hasNext()) {
                BaseLogUtils.info(logger, "upload", "文件上传C", CurrentThreadContext.getCurrentUserName());
                // 取得上传文件
                List<MultipartFile> fileList = multipartRequest.getFiles(iter.next());
                for (MultipartFile f : fileList) {
                    BaseLogUtils.info(logger, "upload", "文件上传D", CurrentThreadContext.getCurrentUserName());
                    if (f != null) {
                        // 取得当前上传文件的文件名称
                        String myFileName = f.getOriginalFilename();
                        // 取得当前上传文件的大小
                        // Long size = f.getSize();
                        // 如果名称不为"",说明该文件存在，否则说明该文件不存在
                        if (StringUtils.isNotEmpty(myFileName)) {
                            com.alibaba.fastjson.JSONObject fileParam = new com.alibaba.fastjson.JSONObject();
                            String _ext = myFileName.substring(myFileName.lastIndexOf("."));
                            String randomFileName = UUID.randomUUID().toString().replace("-", "");
                            String fileName = randomFileName + _ext;
                            // 定义上传路径
                            String path = savePath.toString() + fileName;
                            fileParam.put("fileNm", myFileName);
                            String serverPath = /* serverPrefixPath + */ path.replace(prifixPath, "");
                            fileParam.put("filePath", serverPath);
                            fileParams.add(fileParam);
                            File localFile = new File(path);
                            f.transferTo(localFile);
                        }
                    }
                }

            }
            BaseLogUtils.info(logger, "upload", "文件上传E", CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            BaseLogUtils.info(logger, "fileUpload", "文件上传失败.ERROR", CurrentThreadContext.getCurrentUserName(),ex);
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, ex.getMessage());
        } catch (Exception ex) {
            BaseLogUtils.error(logger, "fileUpload", "文件上传失败,系统错误.ERROR" ,CurrentThreadContext.getCurrentUserName(), ex);
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "系统异常!");
        }
        return fileParams;
    }

}
